<template>
    <div class="table">
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="delete" class="handle-del mr10" @click="delAll">批量删除</el-button>
                <el-select v-model="select_cate"
                           placeholder="筛选分类"
                           class="handle-select mr10"
                           @change="cateSelect">
                    <el-option
                      v-for="item in all"
                      :key="item.id"
                      :label="item.p_name"
                      :value="item.id">
                    </el-option>
                </el-select>
                <el-button type="success" icon="search" @click="add" style="margin-left: 760px">新增</el-button>
            </div>
            <el-table v-loading="loading" :data="tableData" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" label="名称" width="150">
                </el-table-column>
                <el-table-column prop="orderindex" label="排序" width="150">
                    <template scope="scope">
                        <el-input-number v-model="scope.row.orderindex" @change="handleChange(scope.$index,scope.row)" :min="0" :max="10000" label="描述文字"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="is_show" label="是否显示" width="150">
                    <template scope="scope">
                        <el-switch
                          on-text ="是"
                          off-text = "否"
                          on-color="#5B7BFA"
                          off-color="#dadde5"
                          v-model="scope.row.is_show"
                          @change=update(scope.$index,scope.row)>
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="imgurl" label="图片" width="250">
                    <template slot-scope="scope">
                        <img :src="scope.row.imgurl"
                             alt=""
                             style="width: 50px;height: 50px"
                             @click="handleImg(scope.$index, scope.row)">
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="135">
                    <template slot-scope="scope">
                        <!--<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->
                        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--<div class="pagination">-->
                <!--<el-pagination @current-change="handleCurrentChange" layout="prev, pager, next" :total="100">-->
                <!--</el-pagination>-->
            <!--</div>-->
        </div>
        <!-- 图片弹出框 -->
        <el-dialog title="更改图片" :visible.sync="imgVisible" width="30%">
                <div class="crop-demo">
                    <img :src="cropImg" class="pre-img">
                    <div class="crop-demo-btn">选择图片
                        <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage"/>
                    </div>
                    <el-button size="medium" type="success" @click="saveImg">确定</el-button>
                </div>
        </el-dialog>
        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="30%">
            <el-form ref="form" :model="form" label-width="50px">
              <el-form-item label="名称">
                <el-select v-model="add_select_name"
                           placeholder="名称选择"
                           class="handle-select mr10">
                  <el-option
                    v-for="item in names"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="排序">
                  <el-input-number v-model="add_orderindex" :min="0" :max="10000"></el-input-number>
              </el-form-item>
              <el-form-item label="是否显示">
                <el-switch
                  on-text ="是"
                  off-text = "否"
                  on-color="#5B7BFA"
                  off-color="#dadde5"
                  v-model="add_is_show">
                </el-switch>
              </el-form-item>
              <el-form-item label="http图片">
                <el-input v-model="add_imgurl2" placeholder="http地址" @change="imgurl"></el-input>
                <img :src="error_imgurl" v-show="add_imgurl2" class="pre-img http_img" @error="imgError"/>
              </el-form-item>
              <el-form-item label="本地图片">
                <img :src="add_imgurl" class="pre-img">
                <input type="file"
                       class="add_input"
                       name="image"
                       accept="image/*"
                       @change="addImg"/>
              </el-form-item>
              <el-form-item label="分类">
                <el-select v-model="add_select_cate"
                           placeholder="分类选择"
                           class="handle-select mr10">
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.p_name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
  import VueCropper  from 'vue-cropperjs';
    export default {
        data() {
            return {
                tableData: [],
                cur_page: 1,
                multipleSelection: [],
                select_cate: '',
                select_word: '',
                del_list: [],
                is_search: false,
                addVisible: false,
                delVisible: false,
                imgVisible:false,
                form: {
                    name: '',
                    orderindex: '',
                    is_show: '',
                    imgurl: '',
                    p_name: ''
                },
                idx: -1,
              fileList: [],
              imgSrc: '',
              cropImg: '',
              id:'',
              options:'',
              loading: false,
              delId:'',
              add_select_cate:'',
              add_select_name:'',
              add_orderindex:0,
              add_is_show:true,
              add_imgurl:'./static/img/upload.png',
              add_imgurl2:'',
              error_imgurl:'',
              names:[],
              all:[]
            }
        },
          components: {
            VueCropper
          },
        created() {
            this.getData();
            this.getFullChildCate();
        },
        computed: {
        },
        methods: {
            // 获取数据
            getData() {
              this.loading = true
                this.$axios.get('http://www.scott.com/htapi/index/bannerList', {
                }).then((res) => {
                  for(var i in res.data){
                    if(res.data[i].is_show == 1){
                      res.data[i].is_show = true
                    } else {
                      res.data[i].is_show = false
                    }
                  }
                  this.tableData = res.data;
                  this.loading = false
                })
              this.$axios.get('https://dttx.0576sj.com/moblie/tongji/getcollection', {
              }).then((res) => {
                var obj ={
                  id: '',
                  orderindex: '',
                  p_name:'全部'
                }
                this.options = res.data;
                this.all = this.options.slice(0);
                this.all.splice(0,0,obj)
              })
            },
            search() {
                this.is_search = true;
            },
          //显示图片弹出框
          handleImg(index, data) {
            this.cropImg = data.imgurl;
            this.imgVisible = true;
            this.id = data.id
            this.index = index
          },
            handleDelete(index, data) {
                this.idx = index;
                this.delId = data.id
                this.delVisible = true;
            },
            //批量删除
            delAll() {
                const arr = []
                let self = this
                for(var i in this.multipleSelection){
                  arr.push(this.multipleSelection[i].id)
                }
                var arrNew = JSON.stringify(arr)
              this.$axios.post(`https://dttx.0576sj.com/moblie/tongji/deleteChildCate`, self.qs.stringify({
                id:arrNew
              })).then((res) => {
                for(var i in this.tableData){
                  for(var j in arr)
                  if(this.tableData[i].id == arr[j]){
                    self.tableData.splice(i, 1);
                  }
                }
                self.$message.success('删除成功');
                self.delVisible = false;
              })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
          //获取名称下拉
            getFullChildCate(){
              let self = this
              this.$axios.get('https://dttx.0576sj.com/moblie/tongji/getFullChildCate', {
              }).then((res) => {
                self.names = res.data
              })
          },
          imgurl(){
            this.error_imgurl = this.add_imgurl2
          },
          imgError(){
            this.error_imgurl = './static/img/error.png'
          },
            // 保存新增
            saveAdd() {
              let self = this
              if(self.add_is_show){
                self.add_is_show = 1
              } else {
                self.add_is_show = 0
              }
              var dataArr = [
                self.add_select_cate,
                self.add_select_name,
                self.add_imgurl,
              ];
              for(var i in dataArr){
                if(!dataArr[i]){
                  self.$message.error('请填写完整');
                  self.add_is_show = true
                  return
                }
              }
              if(self.add_imgurl == './static/img/upload.png' && !self.add_imgurl2){
                self.$message.error('请上传图片');
                self.add_is_show = true
                return
              }
              var http_img = $('.http_img').attr('src')
              if(self.add_imgurl == './static/img/upload.png' && http_img == './static/img/error.png'){
                self.$message.error('图片地址有误');
                self.add_is_show = true
                return
              }
              var data = {}
              if(self.add_imgurl2 && http_img != './static/img/error.png'){
                data = {
                  category_id: self.add_select_cate,
                  brand_id:self.add_select_name,
                  orderindex:self.add_orderindex,
                  is_show:self.add_is_show,
                  imgurl2:self.add_imgurl2
                }
              } else {
                data = {
                  category_id: self.add_select_cate,
                  brand_id:self.add_select_name,
                  orderindex:self.add_orderindex,
                  is_show:self.add_is_show,
                  imgurl:self.add_imgurl
                }
              }
              this.$axios.post(`https://dttx.0576sj.com/moblie/tongji/insertChildCate`, self.qs.stringify(data)).then((res) => {
                  if(res.data.code == 0){
                    self.$message.error(res.data.msg);
                    self.add_is_show = true
                    return
                  }
                  self.$message.success('新增成功');
                  self.add_is_show = true
                  self.getData();
              })
            },
            // 确定删除
            deleteRow(){
              let self = this
              var arr = JSON.stringify([self.delId]);
              this.$axios.post(`https://dttx.0576sj.com/moblie/tongji/deleteChildCate`, self.qs.stringify({
                    id:arr
                })).then((res) => {
                self.tableData.splice(self.idx, 1);
                self.$message.success('删除成功');
                self.delVisible = false;
              })
            },
          //新增
          add(){
            this.addVisible = true
          },
          //是否显示
          update(index,data){
            let self = this
            var is_show = ''
            if(data.is_show){
              is_show = 1
            } else {
              is_show = 0
            }
            this.$axios.post(`https://dttx.0576sj.com/moblie/tongji/updateChildCate`, self.qs.stringify({
              id:data.id,
              is_show:is_show
            })).then((res) => {
            })
          },
          //排序
          handleChange(index,data){
            let self = this
            this.$axios.post(`https://dttx.0576sj.com/moblie/tongji/updateChildCate`, self.qs.stringify({
              id:data.id,
              orderindex:data.orderindex
            })).then((res) => {
            })
          },
          //图片
          setImage(e){
            let self = this;
            var AllowImgFileSize = 2100000;
            const file = e.target.files[0];
            const reader = new FileReader();
            var imgUrlBase64;
            if (file) {
              //将文件以Data URL形式读入页面
              imgUrlBase64 = reader.readAsDataURL(file);
              reader.onload = function (e) {
                //var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分（可选可不选，需要与后台沟通）
                if (AllowImgFileSize != 0 && AllowImgFileSize < reader.result.length) {
                  alert( '上传失败，请上传不大于2M的图片！');
                  return;
                }else{
                  //执行上传操作
                  self.cropImg = reader.result;
                }
              }
            }
          },
          //新增图片
          addImg(e){
            let self = this;
            var AllowImgFileSize = 2100000;
            const file = e.target.files[0];
            const reader = new FileReader();
            var imgUrlBase64;
            if (file) {
              //将文件以Data URL形式读入页面
              imgUrlBase64 = reader.readAsDataURL(file);
              reader.onload = function (e) {
                //var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分（可选可不选，需要与后台沟通）
                if (AllowImgFileSize != 0 && AllowImgFileSize < reader.result.length) {
                  alert( '上传失败，请上传不大于2M的图片！');
                  return;
                }else{
                  //执行上传操作
                  self.add_imgurl = reader.result;
                }
              }
            }
          },
          //保存图片
          saveImg(){
            let self = this
            this.$axios.post(`https://dttx.0576sj.com/moblie/tongji/updateChildCate`,self.qs.stringify({
              id:self.id,
              imgurl:self.cropImg
            })).then((res) => {
              self.tableData[self.index].imgurl = self.cropImg;
              self.imgVisible = false;
            })
          },
          //分类改变
          pNameChange(index,data){
            let self = this
            this.$axios.post(`https://dttx.0576sj.com/moblie/tongji/updateChildCate`,self.qs.stringify({
              id:data.id,
              category_id:data.p_name,
              brand_id:data.brand_id
            })).then((res) => {
              if(res.data.code == 0){
                self.$message.error(res.data.msg);
                self.getData();
              }
            })
          },
          //筛选分类
          cateSelect(){
              let self = this
            this.$axios.get(`https://dttx.0576sj.com/moblie/tongji/getChildCate?category_id=${self.select_cate}`, {
            }).then((res) => {
              for(var i in res.data){
                if(res.data[i].is_show == 1){
                  res.data[i].is_show = true
                } else {
                  res.data[i].is_show = false
                }
              }
              this.tableData = res.data;
              this.loading = false
            })
          }
        }
    }

</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    .content-title{
        font-weight: 400;
        line-height: 50px;
        margin: 10px 0;
        font-size: 22px;
        color: #1f2f3d;
    }
    .pre-img{
        width: 100px;
        height: 100px;
        background: #f8f8f8;
        border: 1px solid #eee;
        border-radius: 5px;
    }
    .crop-demo{
        display: flex;
        align-items: center;
      justify-content: center;
      flex-direction: column;
    }
    .crop-demo-btn{
        position: relative;
        width: 100px;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        background-color: #409eff;
        color: #fff;
        font-size: 14px;
        border-radius: 4px;
        box-sizing: border-box;
      margin-top: 10px;
      margin-bottom: 10px;
    }
    .crop-input{
        position: absolute;
        width: 100px;
        height: 40px;
        left: 0;
        top: 0;
        opacity: 0;
        cursor: pointer;
    }
  .add_input{
    width: 102px;
    height: 102px;
    position: absolute;
    left: 50px;
    top: 0;
    opacity: 0;
  }
</style>
